package csu.fun.spring_store.persistence;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import csu.fun.spring_store.domain.Category;
import csu.fun.spring_store.domain.Product;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CategoryMapper extends BaseMapper<Category> {

    @Results({
            @Result(column = "catid", property = "categoryid"),
            @Result(column = "catid", property = "products",
                    many = @Many(select ="csu.fun.spring_store.persistence.ProductMapper.selectBycatid"))
    })
    @Select("SELECT * FROM category WHERE catid = #{id}")
    Category getCategoryById(String id);

    //判断是否存在指定id的category（categoryid不区分大小写）
    default boolean isExistCategory(String categoryid) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catid", categoryid);
        return this.exists(queryWrapper);
    }

    //返回指定id的category
    default Category getCategoryByUserid(String categoryid) {
        return this.selectById(categoryid);
    }

    //插入一个新category，返回实际操作的行数。category不为null且categoryid必须不在数据库中存在，否则不进行任何修改
    default int setNewCategory(Category category) {
        if (category == null) {
            return 0;
        }
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catid", category.getCategoryid());
        if (!this.exists(queryWrapper)) {
            return this.insert(category);
        }
        return 0;
    }

    //一次性更新整条记录，返回实际修改的行数。category不为null且categoryid必须已经在数据库中存在，否则不进行任何修改
    default int setExistProduct(Category category) {
        if (category != null) {
            return this.updateById(category);
        }
        return 0;
    }

    /*
      单独修改数据库中的某个值，返回实际修改的行数。productid必须已经在数据库中存在，否则不进行任何修改
     */
    default int setNameByCategoryid(String categoryid, String name) {
        Category category = this.selectById(categoryid);
        if (category != null) {
            category.setName(name);
            return this.updateById(category);
        }
        return 0;
    }
    default int setDescnByCategoryid(String categoryid, String descn) {
        Category category = this.selectById(categoryid);
        if (category != null) {
            category.setDescn(descn);
            return this.updateById(category);
        }
        return 0;
    }

    //删除指定id的category，返回实际操作的行数
    default int removeCategoryByCategoryid(String categoryid) {
        return this.deleteById(categoryid);
    }
}
